<template>
  <el-card class="login-container">
    <h2>用户登录</h2>
    <el-form @submit.prevent="handleLogin" label-position="top">
      <el-form-item label="用户名">
        <el-input v-model="user.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="user.password" placeholder="请输入密码" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleLogin">登录</el-button>
        <el-button type="text" @click="navigateToRegister">注册</el-button> <!-- 注册按钮 -->
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import {reactive} from 'vue';
import {useRouter} from 'vue-router';
import {ElMessage} from 'element-plus';
import {sm3} from 'sm-crypto';
import {resetReactive} from '@/utils/index';
import { userLogin } from '@/api/user';

let user = reactive({
  username: '',
  password: '',
  smPassword: '',
});

const router = useRouter();

// 处理登录逻辑
const handleLogin = async () => {
  user.smPassword = sm3(user.password);
  // 组装body
  const body = {
    username: user.username,
    password: user.smPassword
  }
  // 调用登录接口
  const response = await userLogin(body);
  //清空输入框
  resetReactive(user);
  // 判断登陆情况
  if (response.data.code === 200) {
    //登录成功
    // 保存token
    localStorage.setItem('token', response.headers['authorization']);
    ElMessage.success('登录成功');
    await router.push('/index'); // 登录成功后跳转到 MainLayout
  } else {
    ElMessage.error(response.data.errorMessage);
  }
};

// 导航到注册页面
const navigateToRegister = () => {
  router.push('/register');
};
</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 150px auto;
  padding: 20px;
}
</style>
